package cn.enjoy.tool.base;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

public class StreamTest {

    public static void main(String[] args) {
        List<Obj> objList = Lists.newArrayList(new Obj(1, "水果"), new Obj(2, "苹果"), new Obj(3, "香蕉"), new Obj(1, "水果2"));
        Map<Integer, List<Obj>> collect = objList.stream().collect(Collectors.groupingBy(Obj::getId));
        for (Map.Entry<Integer, List<Obj>> integerListEntry : collect.entrySet()) {
            System.out.println(integerListEntry.getKey());
        }
        List<Obj> orDefault = collect.getOrDefault(1, Collections.emptyList());
        System.out.println(collect.entrySet());
        System.out.println(orDefault.toString());

        List<String> k = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            k.add("abc" + String.valueOf(i));
        }
        System.out.println(k.toString());
        List<String> stringList = k.stream().filter(t -> !t.contains("5")).collect(toList());
        Map<String, String> stringStringMap = k.stream().collect(Collectors.toMap(t -> t.substring(3), t -> t));
        System.out.println(stringStringMap.entrySet());
        System.out.println(stringList.toString());

        List<List<Integer>> outer = new ArrayList<>();
        List<Integer> inner1 = new ArrayList<>();
        inner1.add(1);
        List<Integer> inner2 = new ArrayList<>();
        inner1.add(2);
        List<Integer> inner3 = new ArrayList<>();
        inner1.add(3);
        outer.add(inner1);
        outer.add(inner2);
        outer.add(inner3);
        //把流中集合装换为流
        List<Integer> result = outer.stream().flatMap(inner -> inner.stream().map(i -> i + 1)).collect(toList());
        System.out.println(result);
        System.out.println("############");
    }

    static class Obj {
        int id;
        String name;

        Obj(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "Obj{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}